<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="出发地" prop="departureRegionName">
        <el-input
          v-model="queryParams.departureRegionName"
          placeholder="请输入出发地"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目的地" prop="destinationRegionName">
        <el-input
          v-model="queryParams.destinationRegionName"
          placeholder="请输入目的地"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="vendorName">
        <el-input
          v-model="queryParams.vendorName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成人价" prop="adultPrice">
        <el-input
          v-model="queryParams.adultPrice"
          placeholder="请输入成人价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="儿童价" prop="childPrice">
        <el-input
          v-model="queryParams.childPrice"
          placeholder="请输入儿童价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="婴儿价" prop="infantPrice">
        <el-input
          v-model="queryParams.infantPrice"
          placeholder="请输入婴儿价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行程天数" prop="travelDays">
        <el-input
          v-model="queryParams.travelDays"
          placeholder="请输入行程天数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行程晚数" prop="travelNights">
        <el-input
          v-model="queryParams.travelNights"
          placeholder="请输入行程晚数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最低成团人数" prop="minPeople">
        <el-input
          v-model="queryParams.minPeople"
          placeholder="请输入最低成团人数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最大成团人数" prop="maxPeople">
        <el-input
          v-model="queryParams.maxPeople"
          placeholder="请输入最大成团人数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否热门产品" prop="isHot">
        <el-select
          v-model="queryParams.isHot"
          placeholder="请选择是否热门产品" style="width: 190px;">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" prop="isActive">
        <el-select
          v-model="queryParams.isActive"
          placeholder="请选择是否上架" style="width: 190px;">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售数量" prop="salesCount">
        <el-input
          v-model="queryParams.salesCount"
          placeholder="请输入销售数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评价数量" prop="commentCount">
        <el-input
          v-model="queryParams.commentCount"
          placeholder="请输入评价数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="平均评分" prop="averageScore">
        <el-input
          v-model="queryParams.averageScore"
          placeholder="请输入平均评分"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['travel:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['travel:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['travel:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['travel:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品类型" align="center" prop="productType">
        <template #default="scope">
          {{ {
            '1': '跟团游', 
            '2': '自由行', 
            '3': '定制游', 
            '4': '半自助游'
          }[scope.row.productType] || '未知类型' }}
        </template>
      </el-table-column>
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <el-table-column label="出发地" align="center" prop="departureRegionName" />
      <el-table-column label="目的地" align="center" prop="destinationRegionName" />
      <el-table-column label="供应商名称" align="center" prop="vendorName" />
      <el-table-column label="产品详情描述" align="center" prop="description" />
      <el-table-column label="产品亮点" align="center" prop="highlight">
        <template #default="scope">
          <el-tooltip effect="dark" :content="scope.row.highlight" placement="top">
            <div class="text-ellipsis" style="width: 200px;">{{ scope.row.highlight }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="图片URL集合" align="center" prop="imageUrls" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrls" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="成人价" align="center" prop="adultPrice" />
      <el-table-column label="儿童价" align="center" prop="childPrice" />
      <el-table-column label="婴儿价" align="center" prop="infantPrice" />
      <el-table-column label="行程天数" align="center" prop="travelDays" />
      <el-table-column label="行程晚数" align="center" prop="travelNights" />
      <el-table-column label="服务标准" align="center" prop="serviceStandard" />
      <el-table-column label="预订须知" align="center" prop="bookingNotice" />
      <el-table-column label="退改政策" align="center" prop="refundPolicy" />
      <el-table-column label="最低成团人数" align="center" prop="minPeople" />
      <el-table-column label="最大成团人数" align="center" prop="maxPeople" />
      <el-table-column label="是否热门产品" align="center" prop="isHot">
        <template #default="scope">
          {{ scope.row.isHot===1?'是':'否' }}
        </template>
      </el-table-column>
      <el-table-column label="是否上架" align="center" prop="isActive">
        <template #default="scope">
          {{ scope.row.isActive===1?'是':'否' }}
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" prop="salesCount" />
      <el-table-column label="评价数量" align="center" prop="commentCount" />
      <el-table-column label="平均评分" align="center" prop="averageScore" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['travel:product:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['travel:product:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改旅游产品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <el-select
            v-model="form.productType"
            placeholder="请选择产品类型">
            <el-option label="跟团游" value="1"></el-option>
            <el-option label="自由行" value="2"></el-option>
            <el-option label="定制游" value="3"></el-option>
            <el-option label="半自助游" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编码" prop="productCode">
          <el-input v-model="form.productCode" disabled  />
        </el-form-item>
        <el-form-item label="出发地" prop="departureRegionName">
          <el-cascader
            v-model="form.departureRegionArray"
            :options="cityOptions"
            :props="cityProps"
            placeholder="请选择出发地"
            clearable
            @change="() => { form.departureRegionName = form.departureRegionArray.join('/') || '' }"
            />
        </el-form-item>
        <el-form-item label="目的地" prop="destinationRegionName">
          <el-cascader
            v-model="form.destinationRegionArray"
            :options="cityOptions"
            :props="cityProps"
            placeholder="请选择出发地"
            clearable
            @change="() => { form.destinationRegionName = form.destinationRegionArray.join('/') || '' }"
            />
        </el-form-item>
        <el-form-item label="产品详情描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="产品亮点" prop="highlight">
          <el-input v-model="form.highlight" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片URL集合" prop="imageUrls">
          <image-upload v-model="form.imageUrls"/>
        </el-form-item>
        <el-form-item label="成人价" prop="adultPrice">
          <el-input v-model="form.adultPrice" placeholder="请输入成人价" />
        </el-form-item>
        <el-form-item label="儿童价" prop="childPrice">
          <el-input v-model="form.childPrice" placeholder="请输入儿童价" />
        </el-form-item>
        <el-form-item label="婴儿价" prop="infantPrice">
          <el-input v-model="form.infantPrice" placeholder="请输入婴儿价" />
        </el-form-item>
        <el-form-item label="行程天数" prop="travelDays">
          <el-input v-model="form.travelDays" placeholder="请输入行程天数" />
        </el-form-item>
        <el-form-item label="行程晚数" prop="travelNights">
          <el-input v-model="form.travelNights" placeholder="请输入行程晚数" />
        </el-form-item>
        <el-form-item label="服务标准" prop="serviceStandard">
          <el-input v-model="form.serviceStandard" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="预订须知" prop="bookingNotice">
          <el-input v-model="form.bookingNotice" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="退改政策" prop="refundPolicy">
          <el-input v-model="form.refundPolicy" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="最低成团人数" prop="minPeople">
          <el-input v-model="form.minPeople" placeholder="请输入最低成团人数" />
        </el-form-item>
        <el-form-item label="最大成团人数" prop="maxPeople">
          <el-input v-model="form.maxPeople" placeholder="请输入最大成团人数" />
        </el-form-item>
        <el-form-item label="是否上架" prop="isActive">
          <el-select
            v-model="form.isActive"
            placeholder="请选择是否上架">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请选择标签大类" prop="tagCategory">
          <el-select
              v-model="form.tagCategory" multiple
              placeholder="请选择标签大类"
              clearable
              style="width: 100%" @change="handleTagCategoryChange">
              <el-option
                v-for="item in tagCategoryOptions"
                :key="item.value"
                :label="item.label"  
                :value="item.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="请选择景点标签" prop="tagIds">
          <el-select
              v-model="selectedTagids" multiple
              placeholder="请选择景点标签"
              clearable
              style="width: 100%">
              <el-option
                v-for="item in tagNameOptions"
                :key="item.value"
                :label="item.label"  
                :value="item.value"
              />
            </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct,getProductTotal,getCityCascaderData } from "@/api/travel/product"
import { getTagCategoryList,listByCategory } from "@/api/travel/tag"
const { proxy } = getCurrentInstance()

const productList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const cityOptions = ref([])
const cityProps = {
  value: 'value',
  label: 'label', 
  children: 'children'
}
const tagCategoryOptions = ref([])
const tagNameOptions = ref([])
const selectedTagids = ref([])

const data = reactive({
  form: {
    productCode: '',
    departureRegionName: '',
    destinationRegionName: '',
    departureRegionArray: [], 
    destinationRegionArray: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null,
    productCode: null,
    productType: null,
    departureRegionName: null,
    destinationRegionName: null,
    vendorId: null,
    vendorName: null,
    description: null,
    highlight: null,
    imageUrls: null,
    adultPrice: null,
    childPrice: null,
    infantPrice: null,
    travelDays: null,
    travelNights: null,
    serviceStandard: null,
    bookingNotice: null,
    refundPolicy: null,
    minPeople: null,
    maxPeople: null,
    isHot: null,
    isActive: null,
    salesCount: null,
    commentCount: null,
    averageScore: null,
  },
  rules: {
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    productType: [
      { required: true, message: "产品类型：1-跟团游 2-自由行 3-定制游 4-半自助游不能为空", trigger: "change" }
    ],
    adultPrice: [
      { required: true, message: "成人价不能为空", trigger: "blur" },
      { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入有效的金额（最多两位小数）", trigger: "blur" }
    ],
    childPrice: [
      { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入有效的金额（最多两位小数）", trigger: "blur" }
    ],
    infantPrice: [
      { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入有效的金额（最多两位小数）", trigger: "blur" }
    ],
    travelDays: [
      { required: true, message: "行程天数不能为空", trigger: "blur" },
      { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" }
    ],
    travelNights: [
      { required: true, message: "行程晚数不能为空", trigger: "blur" },
      { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" }
    ],
    minPeople: [
      { pattern: /^[1-9]\d*$/, message: "最低成团人数请输入正整数", trigger: "blur" }
    ],
    maxPeople: [
      { pattern: /^[1-9]\d*$/, message: "最大成团人数请输入正整数", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询旅游产品列表 */
function getList() {
  loading.value = true
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    productId: null,
    productName: null,
    productCode: null,
    productType: null,
    departureRegionName: null,
    destinationRegionName: null,
    departureRegionArray: [], 
    destinationRegionArray: [],
    vendorId: null,
    vendorName: null,
    description: null,
    highlight: null,
    imageUrls: null,
    adultPrice: null,
    childPrice: null,
    infantPrice: null,
    travelDays: null,
    travelNights: null,
    serviceStandard: null,
    bookingNotice: null,
    refundPolicy: null,
    minPeople: null,
    maxPeople: null,
    isHot: null,
    isActive: null,
    salesCount: null,
    commentCount: null,
    averageScore: null,
    createTime: null,
    updateTime: null,
    tagIds: []
  }
  selectedTagids.value = [];
  proxy.resetForm("productRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.productId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}


// 生成产品编码的函数
const generateProductCode = () => {
  const businessPrefix = 'TP'; // 业务标识
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const dateStr = `${year}${month}${day}`;
  const serialNumber = '001'; // 实际开发中，需调用后端接口获取当日序列号
  getProductTotal().then(response => {
    const totalNum = response.data || 0;
    const serialNumber = String(totalNum + 1).padStart(3, '0'); // 用产品总数作为序列号（仅临时兼容，不推荐长期用）
    form.value.productCode = `${businessPrefix}${dateStr}${serialNumber}`;
  }).catch(error => {
    console.error('获取当日序列号失败：', error);
  });
  form.value.productCode = `${businessPrefix}${dateStr}${serialNumber}`;
}

const fetchCityData = async () => {
  try {
    const res = await getCityCascaderData();
    if (res.code === 200) { 
      cityOptions.value = res.data.map(item => ({
        value: item.label,   // 将value改为中文名称（如“辽宁省”）
        label: item.label,   // 显示文本仍为中文名称
        children: item.children?.map(child => ({
          value: child.label, // 子级value也改为中文名称（如“沈阳市”）
          label: child.label,
          children: child.children || []
        })) || []
      }));
    } else {
      console.error('获取城市数据失败：', res.msg);
    }
  } catch (err) {
    console.error('获取城市数据异常：', err);
  }
}

function fetchTagCategory() {
  getTagCategoryList().then(response => {
    tagCategoryOptions.value = response.data.map(item => ({
      label: item.desc, // 显示文本
      value: item.code  // 实际存储值（枚举code）
    }));
  }).catch(error => {
    console.error("获取标签大类枚举失败：", error)
  })
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加旅游产品"
  generateProductCode()
  fetchCityData()
  fetchTagCategory()
}

function handleTagCategoryChange(selectedTags) {
  if(selectedTags.length===0){
    tagNameOptions.value = [];
    return;
  }
  const query = {
    tagCategorys: selectedTags
  };
  listByCategory(query).then(res => {
    if (res.code === 200) {
      tagNameOptions.value = res.rows.map(item => ({
        value: item.tagId,
        label: item.tagName
      }));
    }
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _productId = row.productId || ids.value
  getProduct(_productId).then(response => {
    form.value = response.data
    selectedTagids.value = form.value.tagIds || []
    open.value = true
    title.value = "修改旅游产品"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      form.value.tagIds = selectedTagids.value;
      if (form.value.productId != null) {
        console.log(form.value.departureRegionName);
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _productIds = row.productId || ids.value
  proxy.$modal.confirm('是否确认删除旅游产品编号为"' + _productIds + '"的数据项？').then(function() {
    return delProduct(_productIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('travel/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
</style>